//
//  MusicPlayViewController.m
//  Project_B
//
//  Created by dllo on 15/12/2.
//  Copyright © 2015年 张闯. All rights reserved.
//

#import "MusicPlayViewController.h"
#import "MusicModel.h"
#import "RCNetWorking.h"
#import "UIImageView+WebCache.h"
#import "XPQScrollLabel.h"
#import "STKHTTPDataSource.h"
#import "ZCSTKPlayer.h"
#import "MenuViewController.h"

@interface MusicPlayViewController () < STKAudioPlayerDelegate >
@property (nonatomic, strong) UIButton *playButton;
@property (nonatomic, strong) UIButton *upButton;
@property (nonatomic, strong) UIButton *nextButton;
@property (nonatomic, strong) UIProgressView *progressV;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UILabel *beginTime;
@property (nonatomic, strong) UILabel *endTime;
@property (nonatomic, strong) STKDataSource * dataSource;
@property (nonatomic, strong) UISlider *slider;
@property (nonatomic, strong) XPQScrollLabel *title1;
@property (nonatomic, strong) UIImageView *imgView;
@property (nonatomic, strong) UIImageView *middleimg;
@property (nonatomic, strong) NSTimer *times;

@end

@implementation MusicPlayViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"音乐" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self background];
    [self buttonqun];
    [self scrollLabel];
    
    //雪花定时器
    [self setTimes:[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(snow) userInfo:nil repeats:YES]];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(changePlayButton:) name:@"音乐" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    
}

- (void)changePlayButton:(NSNotification *)note
{
    if ([note.object isEqualToString:@"play"]) {
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"playButton"] forState:0];
    } else if ([note.object isEqualToString:@"pause"]) {
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"pauseButton"] forState:0];
    }
}

#pragma mark - 大多数按钮
- (void)buttonqun
{
    //初始化播放器
    self.player = [ZCSTKPlayer shareInstance];
    self.player.delegate = self;
   
    
    self.slider = [[UISlider alloc]initWithFrame:CGRectMake(60, HEIGHT / 1.7, WIDTH - 120, 50)];
    [self.view addSubview:_slider];
    // 小点
    [_slider setThumbImage:[UIImage imageNamed:@"iconfont-yuanquan-2"] forState:UIControlStateNormal];
    [_slider addTarget:self action:@selector(progressSlider:) forControlEvents:UIControlEventValueChanged];
    _slider.minimumTrackTintColor = [UIColor orangeColor];
    
    //初始化播放进度条
//    self.progressV = [[UIProgressView alloc] initWithFrame:CGRectMake(60, HEIGHT / 1.5, WIDTH - 120, 50)];
//    self.progressV.trackTintColor = [UIColor grayColor];
//    self.progressV.progressTintColor = [UIColor orangeColor];
//    [self.view addSubview:self.progressV];
   
    //播放
    self.playButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.playButton.frame = CGRectMake((WIDTH - 50) / 2 , self.slider.frame.origin.y + 50, 50, 50);
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"pauseButton"] forState:UIControlStateNormal];
    [self.view addSubview:self.playButton];
    [self.playButton addTarget:self action:@selector(playButtonAction) forControlEvents:UIControlEventTouchUpInside];//button触发事件
    
    //上一首
    self.upButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.upButton.frame = CGRectMake(WIDTH / 3.5, self.playButton.frame.origin.y + 10, 30, 30);
    [self.view addSubview:self.upButton];
    [self.upButton setBackgroundImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
    [self.upButton addTarget:self action:@selector(upButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    //下一首
    self.nextButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.nextButton.frame = CGRectMake(WIDTH - (WIDTH / 3.5) - 30, self.upButton.frame.origin.y, 30, 30);
    [self.view addSubview:self.nextButton];
    [self.nextButton setBackgroundImage:[UIImage imageNamed:@"nextButton"] forState:UIControlStateNormal];
    [self.nextButton addTarget:self action:@selector(nextButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    //开始时间
    //时间label
    self.beginTime = [[UILabel alloc] initWithFrame:CGRectMake(0, self.slider.frame.origin.y + 8, 50, 30)];
    self.beginTime.textAlignment = NSTextAlignmentRight;
    self.beginTime.text = [NSString stringWithFormat:@"%02ld:%02ld",(NSInteger)(self.player.progress) / 60, (NSInteger)(self.player.progress) % 60 ];
    self.beginTime.textColor = [UIColor grayColor];
    [self.view addSubview:self.beginTime];
    [self.beginTime setFont:[UIFont systemFontOfSize:13]];
    
    //时间label2
    self.endTime = [[UILabel alloc] initWithFrame:CGRectMake(self.slider.frame.origin.x + self.slider.frame.size.width + 5, self.beginTime.frame.origin.y, 50, 30)];
    self.endTime.textColor = [UIColor grayColor];
    self.endTime.text = [NSString stringWithFormat:@"%02ld:%02ld",(NSInteger)(self.player.duration) / 60, (NSInteger)(self.player.duration) % 60 ];
    [self.view addSubview:self.endTime];
    [self.endTime setFont:[UIFont systemFontOfSize:13]];
 
}

#pragma mark - slider滑动事件
- (void)progressSlider:(UISlider *)slider
{
    if (self.player) {
        [self.player seekToTime:slider.value];
    }
}

#pragma mark - 方法
- (void)playButtonAction
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    if ([self.player state] == STKAudioPlayerStatePaused) {
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"pauseButton"] forState:UIControlStateNormal];
        [[self player] resume];
        [center postNotificationName:@"音乐1" object:@"pause" userInfo:nil];
        self.times.fireDate = [NSDate distantPast];
        
    } else if ([[self player] state] == STKAudioPlayerStatePlaying) {
        
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"playButton"] forState:UIControlStateNormal];
        [[self player] pause];
        [center postNotificationName:@"音乐1" object:@"play" userInfo:nil];
        self.times.fireDate = [NSDate distantFuture];
        
    } else {
        
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"pauseButton"] forState:UIControlStateNormal];
        [self playMusic];
    }
}

#pragma mark - 上一首
- (void)upButtonAction
{
    if (self.i == 0) {
        
        self.i = self.musarr.count;
    }
    self.i--;
    //更新视图
    MusicModel * singleM = self.musarr[self.i];
    self.MusiModel = singleM;
    self.title1.text = singleM.title;
    self.title1.type = XPQScrollLabelTypeRepeat;
    [self.imgView sd_setImageWithURL:[NSURL URLWithString:singleM. coverMiddle]];
    [self.middleimg sd_setImageWithURL:[NSURL URLWithString:singleM.coverMiddle]];
    [self playMusic];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"top" object:singleM.title];
    
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"pauseButton"] forState:UIControlStateNormal];
}

#pragma mark - 下一首
- (void)nextButtonAction
{
    self.i++;
    NSLog(@"%ld", self.i);
    if (self.i == self.musarr.count) {
        self.i = 0;
    }
    //更新视图
    MusicModel * singleM = self.musarr[self.i];
    self.MusiModel = singleM;
    self.title1.text = singleM.title;
    self.title1.type = XPQScrollLabelTypeRepeat;
    [self.imgView sd_setImageWithURL:[NSURL URLWithString:singleM.coverMiddle]];
    [self.middleimg sd_setImageWithURL:[NSURL URLWithString:singleM.coverMiddle]];
    [self playMusic];
    
     [[NSNotificationCenter defaultCenter] postNotificationName:@"top" object:singleM.title];
    
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"pauseButton"] forState:UIControlStateNormal];
}

#pragma mark - 准备数据
- (void)playMusic
{
    //网络状态判断
    [RCNetWorking networkReachabilityStatus:^(id result) {
        //判断网络是否有wifi
        if (![result isEqualToNumber:@2]) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否使用流量播放视频" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *canelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            //在没有WiFi的情况下点击确认播放 获取数据
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                // 点击确定按钮执行的代码
                NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@", [self.musarr[self.i] trackId]];
                [RCNetWorking GETDataWithAFN:str cookie:nil completion:^(id result) {
                    NSDictionary *dic = result;
                    [self.player play:dic[@"playUrl64"]];
                    
                } error:^(id error) {
                    
                }];
                [self setTimer:[NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES]];
                
            }];
            // 给alert添加操作
            [alert addAction:canelAction];
            [alert addAction:okAction];
            // 模态显示
            [self presentViewController:alert animated:YES completion:nil];
        } else {
            //有WiFi的情况下不进行提示
            NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@", [self.musarr[self.i] trackId]];
            [RCNetWorking GETDataWithAFN:str cookie:nil completion:^(id result) {
                NSDictionary *dic = result;
                [self.player play:dic[@"playUrl64"]];
                
            } error:^(id error) {
                
            }];
            [self setTimer:[NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES]];
        }
    }];
}

- (void)track
{
    //进度条
    self.slider.maximumValue = self.player.duration;
    self.slider.value = self.player.progress;
    
    //开始时间
    NSInteger beginMin = (NSInteger)[[self player] progress] / 60;
    NSInteger beginSec = (NSInteger)[[self player] progress] % 60;
    [[self beginTime] setText:[NSString stringWithFormat:@"%02ld:%02ld", beginMin, beginSec]];
    //结束时间
    NSInteger endProgress = self.player.duration;
    NSInteger endMin = endProgress / 60;
    NSInteger endSec = endProgress % 60;
    
    [[self endTime] setText:[NSString stringWithFormat:@"%02ld:%02ld", endMin, endSec]];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 播放器协议方法

//SKTPlayer Delegate
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    
    NSLog(@"stop");
    if (audioPlayer.state==STKAudioPlayerStateStopped) {
        [self nextButtonAction];
    }
}


/// Raised when an unexpected and possibly unrecoverable error has occured (usually best to recreate the STKAudioPlauyer)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{
    NSLog(@"错误原因: %d", errorCode);
}


/// Optionally implemented to get logging information from the STKAudioPlayer (used internally for debugging)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer logInfo:(NSString*)line
{
    NSLog(@"信息: %@", line);
}
/// Raised when items queued items are cleared (usually because of a call to play, setDataSource or stop)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didCancelQueuedItems:(NSArray*)queuedItems
{
    NSLog(@"未知");
}


//  代理方法
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"开始播放");
}
/// Raised when an item has finished buffering (may or may not be the currently playing item)
/// This event may be raised multiple times for the same item if seek is invoked on the player
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"完成加载");
}
/// Raised when the state of the player has changed
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
    
}


#pragma mark - 页面将要出现
- (void)viewWillAppear:(BOOL)animated
{
    self.title1.text = self.MusiModel.title;
    self.title1.type = XPQScrollLabelTypeRepeat;
    [self.imgView sd_setImageWithURL:[NSURL URLWithString:self.MusiModel.coverMiddle]];
    [self.middleimg sd_setImageWithURL:[NSURL URLWithString:self.MusiModel.coverMiddle]];
    [self playMusic];
    
    
    
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"pauseButton"] forState:0];

    self.navigationController.navigationBarHidden = YES;
    [self leftButton];
}

#pragma mark - 左按钮
- (void)leftButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"iconfont-fanhui@2x"] forState:UIControlStateNormal];
    button.tintColor = [UIColor whiteColor];
    button.frame = CGRectMake(20, 20, 30, 30);
    [button addTarget:self action:@selector(leftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

#pragma mark - 左按钮方法
- (void)leftButtonAction
{
    self.timer = nil;
    [self.timer invalidate];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 背景图片
- (void)background
{
    //背景图片
    self.imgView = [[UIImageView alloc] initWithFrame:self.view.frame];
    [self.imgView sd_setImageWithURL:[NSURL URLWithString:self.MusiModel.coverMiddle]];
    self.imgView.contentMode = UIViewContentModeScaleAspectFill;
    self.imgView.clipsToBounds = YES;
    [self.view addSubview:self.imgView];
    
    //毛玻璃效果
    UIBlurEffect *effect=[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *effectView=[[UIVisualEffectView alloc]initWithEffect:effect];
    effectView.frame= self.imgView.frame;
    [self.imgView addSubview:effectView];
    
    //中间图片
    self.middleimg = [[UIImageView alloc] initWithFrame:CGRectMake(80, 80, WIDTH - 160, HEIGHT / 2.5)];
    [self.middleimg sd_setImageWithURL:[NSURL URLWithString:self.MusiModel.coverMiddle]];
    [self.view addSubview:self.middleimg];
}

#pragma mark - 移动的头部label
- (void)scrollLabel
{
    self.title1 = [[XPQScrollLabel alloc] initWithFrame:CGRectMake(100, 30, WIDTH - 200, 20)];
    self.title1.textAlignment = NSTextAlignmentCenter;
    self.title1.text = self.MusiModel.title;
    self.title1.font = [UIFont fontWithName:@"Helvetica-Bold" size:17];
    self.title1.textColor = [UIColor whiteColor];
    self.title1.type = XPQScrollLabelTypeRepeat;
    self.title1.time = 5;
    [self.view addSubview:self.title1];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"top" object:self.MusiModel.title];
}


#pragma mark - 雪花效果
-(void)snow
{
    //随机长宽透明度等
    int start= arc4random() % 375;
    int end= arc4random() % 375;
    int width= arc4random() % 25;
    CGFloat time= (arc4random() % 100) / 10 + 5;
    CGFloat alp= (arc4random() % 5) / 10.0 + 0.1;
    UIImage* image= [UIImage imageNamed:@"Music"];
    UIImageView* imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame= CGRectMake(start, -1 * width, width, width);
    imageView.alpha=alp;
    [self.view addSubview:imageView];
    //开始动画
    [UIView beginAnimations:nil context:(__bridge void * _Nullable)(imageView)];
//    [UIView beginAnimations:nil context:CFBridgingstrong(imageView)];
    //动画持续时间
    [UIView setAnimationDuration:time];
    
    if(end>50&&end<270)
    {
        imageView.frame= CGRectMake(end, 270 - width/2, width, width);
        
    }
    else if((end>10&&end<50)||(end>270&&end<310))
        imageView.frame= CGRectMake(end, 400 - width/2, width, width);
    else
        imageView.frame= CGRectMake(end, 480, width, width);
    
    [UIView setAnimationDidStopSelector:@selector(onAnimationComplete:finished:context:)];
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}

- (void)onAnimationComplete:(NSString*)animationID finished:(NSNumber*)finished context:(void*)context
{
     UIImageView* snowView = (__bridge UIImageView *)(context);
    [snowView removeFromSuperview];
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
